// PaymentRecordServiceImpl.java
package com.geek.water.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.geek.water.constant.MessageConstant;
import com.geek.water.entity.PaymentRecord;
import com.geek.water.exception.WaterException;
import com.geek.water.mapper.PaymentRecordMapper;
import com.geek.water.service.PaymentRecordService;
import com.geek.water.vo.PageQueryVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Slf4j
@Service
public class PaymentRecordServiceImpl extends ServiceImpl<PaymentRecordMapper, PaymentRecord> implements PaymentRecordService {

    @Override
    public Page<PaymentRecord> listPayments(PageQueryVO queryVO, Long billId, LocalDateTime startTime, LocalDateTime endTime) {
        try {
            Page<PaymentRecord> page = Page.of(
                    queryVO.getCurrentPage() != null ? queryVO.getCurrentPage() : 1,
                    queryVO.getPageSize() != null ? queryVO.getPageSize() : 10
            );

            LambdaQueryWrapper<PaymentRecord> wrapper = new LambdaQueryWrapper<>();

            if (billId != null) {
                wrapper.eq(PaymentRecord::getBillId, billId);
            }

            if (startTime != null && endTime != null) {
                wrapper.between(PaymentRecord::getPaidAt, startTime, endTime);
            }

            wrapper.orderByDesc(PaymentRecord::getPaidAt);

            return baseMapper.selectPage(page, wrapper);
        } catch (Exception e) {
            log.error("查询支付记录失败", e);
            throw new WaterException(MessageConstant.INTERNAL_ERROR);
        }
    }

    @Override
    @Transactional
    public boolean recordPayment(PaymentRecord paymentRecord) {
        try {
            if (paymentRecord.getBillId() == null || paymentRecord.getAmount() == null) {
                throw new WaterException(MessageConstant.PARAM_INVALID);
            }

            return save(paymentRecord);
        } catch (Exception e) {
            log.error("记录支付失败", e);
            throw new WaterException(MessageConstant.RECORD_PAYMENT_FAIL);
        }
    }
}